﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Niaofei.Injcetion;
using Niaofei.Repository;

namespace Niaofei.HttpApi
{
    /// <summary>
    /// 自动保存中间件
    /// </summary>
    [Injection(typeof(AutoSaveMiddleware))]
    public class AutoSaveMiddleware : IMiddleware
    {
        private readonly IServiceProvider _serviceProvider;

        public AutoSaveMiddleware(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            await next(context);

            var autoSaves = _serviceProvider.GetServices<IDataBaseAutoSave>();

            foreach (var autoSave in autoSaves)
            {
                await autoSave.SaveChangesAsync();
            }
        }
    }
}
